package com.qzdsoft.erpcloud.controller.sys;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.catalina.servlet4preview.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.qzdsoft.erpcloud.controller.BaseController;
import com.qzdsoft.erpcloud.domain.act.CenterCompany;
import com.qzdsoft.erpcloud.domain.sys.SysUser;
import com.qzdsoft.erpcloud.service.act.CenterCompanyService;
import com.qzdsoft.erpcloud.service.sys.Permission;
import com.qzdsoft.erpcloud.service.sys.SysLog;
import com.qzdsoft.erpcloud.service.sys.SysRoleService;
import com.qzdsoft.erpcloud.service.sys.SysUserService;
import com.qzdsoft.erpcloud.vo.query.basic.BasicUserEditInfo;
import com.qzdsoft.erpcloud.vo.query.basic.BasicUserInfo;
import com.qzdsoft.erpcloud.vo.sys.SysUserQueryParam;
import com.qzdsoft.utils.ExceptionUtil;
import com.qzdsoft.utils.SysUtils;
import com.qzdsoft.utils.constant.SystemConstant;
import com.qzdsoft.utils.enums.CommonStatusEnum;
import com.qzdsoft.vo.EnumPo;
import com.qzdsoft.vo.LayTableResponse;
import com.qzdsoft.vo.Response;
import com.qzdsoft.vo.ResultEnum;
import com.qzdsoft.vo.sys.LoginUserType;
import com.qzdsoft.vo.sys.SysLoginTypeEnum;


/**
 * Created by Admin
 * 系统用户
 */
@Controller
@RequestMapping("/sys/user")
public class SysUserController extends BaseController{
	private static final String BASEPATH = "sys/user";
	private static final Logger logger = LoggerFactory.getLogger(SysUserController.class);
    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private CenterCompanyService actCenterCompanyService;
//
//    @Autowired
//    private RedisHelper redisHelper;
     @Autowired
     private SysRoleService sysRoleService;
    /**
     *
     * @param request
     * @param model
     * @return
     */
     @Permission(validate=false)
    @RequestMapping("/index")
    public Object index(HttpServletRequest request, Model model) {

//        List<EnumPo> statusList = new ArrayList<EnumPo>();
//        Map<Object, Object> statusMap = new HashMap<Object, Object>();
//        for(SysUserStatusEnum e : SysUserStatusEnum.values()){
//            SysUtils.enums(statusList, statusMap, e.getKey(), e.getVal());
//        }
//
//        List<EnumPo> agentList = new ArrayList<EnumPo>();
//        Map<Object, Object> agentMap = new HashMap<Object, Object>();
//        for(SysUserAgentEnum e : SysUserAgentEnum.values()){
//            SysUtils.enums(agentList, agentMap, e.getKey(), e.getVal());
//        }
//
//        model.addAttribute("statusList", statusList);
//        model.addAttribute("statusMap", statusMap);
//
//        model.addAttribute("agentList", agentList);
//        model.addAttribute("agentMap", agentMap);
//        
//        model.addAttribute("sysRoleMap", sysRoleService.getAllRoleList());
//        model.addAttribute("actCenterCompanyMap", actCenterCompanyService.getAllCompany());
////        model.addAttribute("sysRoleMap", redisHelper.getSysRoleMap());
////        model.addAttribute("actCenterCompanyMap", redisHelper.getActCenterCompanyMap());
//
////        model.addAttribute("loginType", SessionUtil.getLoggedType(request));
//        model.addAttribute("loginType",1);
//        model.addAttribute("loginTypeUser", SysLoginTypeEnum.user.getKey());
//        model.addAttribute("loginTypeCompany", SysLoginTypeEnum.company.getKey());
        return BASEPATH+"/index";
    }
    @ResponseBody
    @RequestMapping("/data")
    public LayTableResponse<BasicUserInfo> data(HttpServletRequest request, SysUserQueryParam info) {
//        Integer companyId = getUser().getCompanyId();
//        if(null != companyId){
//            param.setCompanyId(companyId);
//        }
//        Integer count = sysUserService.selectDataCount(param.getAccount(), param.getName(), param.getAgent(), param.getStatus(), param.getCompanyId(), param.getRoleId());
//        List list = sysUserService.selectData(param.getAccount(), param.getName(), param.getAgent(), param.getStatus(), param.getCompanyId(), param.getRoleId(), param.getiDisplayStart(), param.getiDisplayLength());
//        return new DataTablePo(count, list, param.getsEcho());
    	if(info.isFirst()) {
    		return LayTableResponse.nullDataPage();
    	}
    	return sysUserService.selectData(info);
    }

    /**
     * 打开新增页面
     */
    @Permission(validate=false)
    @RequestMapping("/addinit")
    public ModelAndView addinit() {
    	ModelAndView mv = new ModelAndView();
    	//状态:
      List<EnumPo> statusList = new ArrayList<EnumPo>();
      Map<Object, Object> statusMap = new HashMap<Object, Object>();
      for(CommonStatusEnum e : CommonStatusEnum.values()){
          SysUtils.enums(statusList, statusMap, e.getKey(), e.getVal());
      }
      mv.addObject("statusList", statusList);
      mv.addObject("typeList", LoginUserType.ALL);
//      mv.addObject("statusMap", statusMap);
      mv.addObject("actCenterCompanyMap", actCenterCompanyService.getAllCompany());
      mv.addObject("sysRoleList", sysRoleService.getAllRoleList());
    	mv.setViewName(BASEPATH+"/add");
    	return mv;
    }
    
    @SysLog(description="系统用户新增保存")
    @ResponseBody
    @RequestMapping("/add")
    public Response add(HttpServletRequest request, BasicUserEditInfo Info) {
    	logger.debug("系统用户新增:user={}",Info);
    	try{
    		 return sysUserService.edit_execute(Info);
    	}catch(Exception e){
    		ExceptionUtil.getStackTrace(e);
    	}
        return new Response(ResultEnum.ERROR);
       
    }
    
    /**
     * 编辑数据
     * @param request
     * @return
     */
    @Permission(validate=false)
    @ResponseBody
    @RequestMapping("/edit")
    public ModelAndView edit(HttpServletRequest request, @RequestParam("id") Integer id) {
       
    	ModelAndView mv = new ModelAndView();
    	//状态:
      List<EnumPo> statusList = new ArrayList<EnumPo>();
      Map<Object, Object> statusMap = new HashMap<Object, Object>();
      for(CommonStatusEnum e : CommonStatusEnum.values()){
          SysUtils.enums(statusList, statusMap, e.getKey(), e.getVal());
      }
      mv.addObject("statusList", statusList);
      mv.addObject("typeList", LoginUserType.ALL);
//      mv.addObject("statusMap", statusMap);
      mv.addObject("actCenterCompanyMap", actCenterCompanyService.getAllCompany());
      mv.addObject("sysRoleList", sysRoleService.getAllRoleList());
      mv.addObject("obj", sysUserService.selectBasicUserById(id));
      mv.setViewName(BASEPATH+"/edit");
  	return mv;
//    	if(null != id){
//            return new Response(ResultEnum.SUCCESS,sysUserService.selectById(id));
//        }
//        return Response.error("param missing...");
    }

    /**
     * 执行编辑
     * @param request
     * @param sysUser
     * @return
     */
    @SysLog(description="系统用户修改保存")
    @ResponseBody
    @RequestMapping("/edit_execute")
    public Response editExecute(HttpServletRequest request, BasicUserEditInfo sysUser) {
    	logger.debug("系统用户修改,id={},user={}",sysUser.getId(),sysUser);
    	try{
    		return sysUserService.edit_execute(sysUser);
    	}catch(Exception e){
    		ExceptionUtil.getStackTrace(e);
    	}
        return new Response(ResultEnum.ERROR);
    }

    /**
     * 根据主键删除,非物理删除
     * @param request
     * @param id
     * @return
     */
    @SysLog(description="系统用户删除")
    @ResponseBody
    @RequestMapping("/del_execute")
    public Response delExecute(HttpServletRequest request, @RequestParam("id") Integer id) {
        try{
        	return sysUserService.del(id);
        }catch(Exception e){
        	ExceptionUtil.getStackTrace(e);
        }
        return new Response(ResultEnum.ERROR);
    }
    /**
     * 修改密码
     * @param id
     * @return
     */
    @Permission(validate=false)
   
    @RequestMapping("/changepwd")
    public ModelAndView changepwd(Integer id) {
    	ModelAndView mv = new ModelAndView();
    	mv.addObject("obj", sysUserService.selectBasicUserById(id));
    	mv.setViewName(BASEPATH+"/passwd");
    	return mv;
    }
    /**
     * 
     * @param id basic_user 的id
     * @param opwd 旧密码
     * @param npd 新密码
     * @param npda 新密码确认
     * @return
     */
    @SysLog(description="系统用户修改密码")
    @RequestMapping("pwd")
    @ResponseBody
    public Response pwdsave(Integer id ,String opwd,String npd,String npda) {
    	logger.debug("系统用户密码修改:id={}",id);
    	return sysUserService.pwdsave(id, opwd, npd, npda);
    }
    
    
    /**
     * 密码相关
     *
     * @param request
     * @param t              类型
     * @param opd           旧密码
     * @param npd           新密码
     * @param npda          新密码再次
     * @return
     */
    @ResponseBody
    @RequestMapping("/passwd")
    public Object passwd(HttpServletRequest request, @RequestParam("t") Integer t, @RequestParam("opd") String opd, @RequestParam("npd") String npd, @RequestParam("npda") String npda) {
        Response response = null;
        if(null != t && (t.equals(1) || t.equals(2)) & StringUtils.isNotBlank(opd) && StringUtils.isNotBlank(npd) && StringUtils.isNotBlank(npda)){
            if(npd.equals(npda)){
                Integer id = null;
                Integer ltype = null;
                if(t.equals(1)){
                    id = getUser().getId();
                    ltype = getUser().getLoginType();
                } else {
                    String idStr = request.getParameter(SystemConstant.idKey);
                    if(StringUtils.isNotBlank(idStr)){
                        id = Integer.parseInt(idStr);
                    } else {
                        response = Response.error("参数不全...");
                    }
                    ltype = Integer.parseInt(request.getParameter("ltype"));
                }

                if(null != id){
                    if(t.equals(1)){            //  修改自己的密码
                        String pwd = null;
                        if(ltype.equals(SysLoginTypeEnum.user.getKey()) || ltype.equals(SysLoginTypeEnum.company_user.getKey())){
                            SysUser sysUser = sysUserService.selectById(id);
                            pwd = sysUser.getPassword();
                        } else if(ltype.equals(SysLoginTypeEnum.company.getKey())){
                            CenterCompany actCenterCompany = actCenterCompanyService.getById(id);
                           // pwd = actCenterCompany.getPassword();
                        }
                        if(!pwd.equals(SysUtils.string2MD5(opd))){
                            response = Response.error("旧密码不正确...");
                            return response;
                        }
                    }

                    if(ltype.equals(SysLoginTypeEnum.user.getKey()) || ltype.equals(SysLoginTypeEnum.company_user.getKey())){
                        SysUser sysUser =  new SysUser();
                        sysUser.setId(id);
                        sysUser.setPassword(SysUtils.string2MD5(npd));
//                        response = sysUserService.saveOrUpd(sysUser);
                    } else if(ltype.equals(SysLoginTypeEnum.company.getKey())){
                        CenterCompany actCenterCompany = new CenterCompany();
                        actCenterCompany.setId(id);
                        //actCenterCompany.setPassword(SysUtils.string2MD5(npd));
//                        response = actCenterCompanyService.edit(actCenterCompany);
                    }

                }

            } else {
                response = Response.error("两次输入密码不一致...");
            }
        } else {
            response = Response.error("参数不全...");
        }

        if(null != response && response.getCode().equals(ResultEnum.SUCCESS.getCode())){
            response.setMessage("密码修改成功!");
        }

        return response;
    }


}
